<template>
  <div class="select-data-list">
    <el-form :model="listQuery" label-width="100px">
      <el-form-item label="数据集名称">
        <el-input
          v-model="listQuery.fileName"
          placeholder="数据集名称"
          size="small"
        />
      </el-form-item>
      <el-form-item label="数据集描述">
        <el-input
          v-model="listQuery.fileDesc"
          placeholder="数据集描述"
          size="small"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          style="width: 100%"
          v-model="listQuery.createTime"
          type="date"
          size="small"
          class="searchDateTime"
          placeholder="创建时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item style="margin-bottom: 5px">
        <el-button type="primary" size="small" @click="handleCurrentChange(1)"
          >查询</el-button
        >
        <el-button size="small" @click="reSetData">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="error">* 请勾选数据集（单选）</div>
    <el-table
      :data="tableData"
      style="width: 100%"
      ref="table"
      v-loading="loading"
      @select="handleSelectionChange"
      :max-height="200"
      :select-on-indeterminate="false"
    >
      <el-table-column type="selection" width="45"></el-table-column>
      <el-table-column
        prop="id"
        label="数据集ID"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="fileName"
        label="数据集名称"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="fileDesc"
        label="数据集描述"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="projectName"
        label="已关联的项目"
        show-overflow-tooltip
      ></el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        :formatter="formatDateTime"
        show-overflow-tooltip
      ></el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <div class="block text-right">
      <el-button
        @click="setViewfile"
        size="mini"
        :disabled="multipleSelection.length !== 1"
        v-show="disabledBtn()"
        >数据预览</el-button
      >
      <el-button
        type="primary"
        @click="importData"
        size="mini"
        :disabled="multipleSelection.length !== 1"
        >导入</el-button
      >
    </div>
    <div class="block text-right">
      <table class="table-text">
        <thead>
          <tr>
            <th v-for="(item, i) in vfTh" :key="i">{{ item }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, i) in vfData" :key="i">
            <td v-for="(it, j) in item" :key="j">{{ it }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
import request from "@/modules/index/utils/request";
import qs from "qs";
import moment from "moment";
import _ from "lodash";
export default {
  name: "selectDataList",
  props: {
    callBack: [Object, Function],
    value: [Object],
    dataType: {
      type: String,
      default: "data_predict",
    },
  },
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 5,
      currentPage: 1, //table当前页数
      listQuery: {
        fileName: "",
        fileDesc: "",
        createTime: null,
      },
      loading: false,
      multipleSelection: [],
      tableHeight: "40%",
      viewFile: [],
    };
  },
  methods: {
    async loadData() {
      const { currentPage, listQuery, pageSize, dataType } = this;
      const { fileName, fileDesc, createTime } = listQuery;
      let date = createTime ? moment(createTime).format("YYYY-MM-DD") : "";
      let data = qs.parse({
        page: currentPage,
        pageSize: pageSize,
        fileName: fileName,
        fileDesc: fileDesc,
        createTimeFrom: date,
        fileTypes: [dataType],
      });
      this.loading = true;
      if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/material-info/search`,
          "post",
          "application/json;charset=UTF-8",
          data,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            console.log(res);
            // TODO： 定制后台数据处理
            if (res.success) {
              let data = res.data;
              this.tableData = data.list;
              this.total = data.rowCount;
              this.loading = false;
            } else {
              this.$message.error(res.msg);
            }
          },
          { once: true }
        );
      } else {
        request({
          url: "/material-info/search", //接口
          method: "post",
          data: data,
        }).then((response) => {
          let result = response.data;
          if (!result.success) {
            return;
          }
          let data = result.data;
          this.tableData = data.list;
          this.total = data.rowCount;
          this.loading = false;
        });
      }
    },

    handleCurrentChange(value) {
      this.page = value;
      this.loadData();
    },
    formatDateTime(row, column, cellValue, index) {
      let result = moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
      return result;
    },
    handleSelectionChange(selection) {
      if (!selection.length) {
        this.multipleSelection = [];
      } else {
        if (!this.multipleSelection.length) {
          this.multipleSelection = selection;
        } else {
          selection.splice(
            selection.findIndex(
              (item) => item.id === this.multipleSelection[0].id
            ),
            1
          );
          this.$refs.table.clearSelection();
          if (selection.length) {
            this.$refs.table.toggleRowSelection(selection[0]);
          }
          this.multipleSelection = selection;
        }
      }
    },
    reSetData() {
      this.listQuery = {
        fileName: "",
        fileDesc: "",
        createTime: null,
      };
      this.page = 1;
      this.loadData();
    },
    importData() {
      if (this.callBack) {
        let record = {},
          file = this.multipleSelection[0];

        this.callBack(file);
      }
    },
    async setViewfile() {
      let dataList = await this.loadViewfile();
      this.viewFile = dataList;
    },
    disabledBtn() {
      let result = false,
        multipleSelection = this.multipleSelection;
      if (multipleSelection.length == 1) {
        if (
          multipleSelection[0].fileType === "data_predict" ||
          multipleSelection[0].fileType === "txt_classify"
        ) {
          result = true;
        }
      }
      return result;
    },
    loadViewfile() {
      let row = this.multipleSelection;
      let data = {
        fileId: row[0].id,
        encoding: "UTF-8",
      };
      return new Promise((resolve, reject) => {
        request({
          url: "/material-info/viewfile", //接口
          method: "get",
          params: data,
        })
          .then((res) => {
            if (res.data.success) {
              resolve(res.data.data);
            } else {
              resolve([]);
              this.$message.error("无返回预览数据！");
            }
          })
          .catch((err) => {
            this.$message.error("获取预览数据失败！");
            reject(err);
          });
      });
    },
  },
  computed: {
    vfTh: function () {
      let viewFile = _.cloneDeep(this.viewFile),
        result = [];
      if (!viewFile || viewFile.length === 0) {
        return result;
      }
      result = viewFile[0];
      return result;
    },
    vfData: function () {
      let viewFile = _.cloneDeep(this.viewFile),
        result = [];
      if (!viewFile || viewFile.length === 0 || viewFile.length === 1) {
        result = viewFile[0];
      }
      result = _.slice(viewFile, 1);
      return result;
    },
  },
  mounted() {
    // 初始化搜索
    this.handleCurrentChange();
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  width: 80%;
  margin: auto;
}
.error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  text-align: left;
}
.text-right {
  text-align: right;
}
table.table-text {
  width: 100%;
  border-collapse: collapse;
  text-align: center;
  border: solid 1px #ccc;
  margin: 7px 0px;
  thead tr {
    background-color: rgba(204, 204, 204, 0.5);
    th {
      font-size: 13px;
      line-height: 20px;
      color: #000;
      letter-spacing: 0.07px;
      font-weight: normal;
      border: solid 1px #ccc;
      & > div {
        padding: 0.4rem 0.3rem;
      }
      &.padding-left {
        width: 0.8rem;
        box-sizing: border-box;
      }
    }
  }
  tbody tr {
    td {
      font-size: 13px;
      white-space: nowrap;
      box-sizing: border-box;
      line-height: 20px;
      letter-spacing: 0.07px;
      font-weight: normal;
      border: solid 1px #ccc;
      & > div {
        padding: 0.4rem 0.3rem;
        & > div {
          padding: 0.2rem 0rem;
        }
      }
    }
    &.padding-left {
      width: 0.8rem;
      box-sizing: border-box;
    }
  }
}
</style>
